package com.whc.controller;

import com.whc.constant.RedisHeader;
import com.whc.dto.GoodsCreateDto;
import com.whc.dto.GoodsRequestDto;
import com.whc.dto.GoodsUpdateDto;
import com.whc.dto.OrderDto;
import com.whc.result.Result;
import com.whc.service.GoodsService;
import com.whc.vo.GoodsVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

/**
 * @author 韦红材
 * @ClassName GoodsController
 * @data 2024/10/22 17:45
 * @Version V1.0
 **/
@RestController
@RequestMapping("/client/goods")
@Slf4j
@Api(tags = "商品接口")
public class GoodsController {

    @Autowired
    private GoodsService goodsService;
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @ApiOperation("购买商品")
    @PutMapping("/buyGoods")
    public Result buyGoods(@RequestBody OrderDto orderDto){
        if(goodsService.buyGoods(orderDto)){
            return Result.success("购买成功");
        }else{
            return Result.error("购买失败");
        }
    }


    @ApiOperation("增加商品的想要数")
    @PutMapping("/addGoodWanters/{goodId}")
    public Result addGoodWanters(@PathVariable Long goodId){
        goodsService.addGoodsWanters(goodId);
        return Result.success();
    }


    @ApiOperation("查询某用户的降价商品")
    @GetMapping("/getCheaperGoods/{userId}")
    public Result<List<GoodsVo>> getCheaperGoods(@PathVariable Long userId){
        if(redisTemplate.hasKey(RedisHeader.goodsHeaderName+"getCheaperGoods"+userId)){
            return Result.success((List<GoodsVo>)redisTemplate.opsForValue().get(RedisHeader.goodsHeaderName+"getCheaperGoods"+userId));
        }
        List<GoodsVo> goodsVos=goodsService.getCheaperGoods(userId);
        redisTemplate.opsForValue().set(RedisHeader.goodsHeaderName+"getCheaperGoods"+userId,goodsVos);
        return Result.success(goodsVos);
    }
    @ApiOperation("查询某用户的有效商品")
    @GetMapping("/getWorksGoods/{userId}")
    public Result<List<GoodsVo>> getWorksGoods(@PathVariable Long userId){
        if(redisTemplate.hasKey(RedisHeader.goodsHeaderName+"getWorksGoods"+userId)){
            return Result.success((List<GoodsVo>)redisTemplate.opsForValue().get(RedisHeader.goodsHeaderName+"getWorksGoods"+userId));
        }
        List<GoodsVo> goodsVos=goodsService.getWorksGoods(userId);
        redisTemplate.opsForValue().set(RedisHeader.goodsHeaderName+"getWorksGoods"+userId,goodsVos);
        return Result.success(goodsVos);
    }
    @ApiOperation("查询某用户的无效商品")
    @GetMapping("/getUnworksGoods/{userId}")
    public Result<List<GoodsVo>> getUnworksGoods(@PathVariable Long userId){
        if(redisTemplate.hasKey(RedisHeader.goodsHeaderName+"getUnworksGoods"+userId)){
            return Result.success((List<GoodsVo>)redisTemplate.opsForValue().get(RedisHeader.goodsHeaderName+"getUnworksGoods"+userId));
        }
        List<GoodsVo> goodsVos=goodsService.getUnworksGoods(userId);
        redisTemplate.opsForValue().set(RedisHeader.goodsHeaderName+"getUnworksGoods"+userId,goodsVos);
        return Result.success(goodsVos);
    }

    @ApiOperation("查询商品根据分类名")
    @GetMapping("/getListByType")
    public Result<List<GoodsVo>> getlistByType(String CategoryName){
        if(redisTemplate.hasKey(RedisHeader.goodsHeaderName+"getListByType"+CategoryName)){
            return Result.success((List<GoodsVo>)redisTemplate.opsForValue().get(RedisHeader.goodsHeaderName+"getListByType"+CategoryName));
        }
        List<GoodsVo> goodsVos = goodsService.SelectGoodsByType(CategoryName);
        redisTemplate.opsForValue().set(RedisHeader.goodsHeaderName+"getListByType"+CategoryName,goodsVos);
        return Result.success(goodsVos);
    }

    @ApiOperation("查询商品根据分类名")
    @GetMapping("/getListByTypetExcept")
    public Result<List<GoodsVo>> getlistByType(String CategoryName,Long id){
//        if(redisTemplate.hasKey(RedisHeader.goodsHeaderName+"getListByType"+CategoryName)){
//            return Result.success((List<GoodsVo>)redisTemplate.opsForValue().get(RedisHeader.goodsHeaderName+"getListByType"+CategoryName));
//        }
        List<GoodsVo> goodsVos = goodsService.SelectGoodsByTypeExcept(CategoryName,id);
//        redisTemplate.opsForValue().set(RedisHeader.goodsHeaderName+"getListByType"+CategoryName,goodsVos);
        return Result.success(goodsVos);
    }

    @ApiOperation("查询所有商品")
    @GetMapping("/getAll")
    public Result<List<GoodsVo>> getAll(){
        if(redisTemplate.hasKey(RedisHeader.goodsHeaderName+"getAll")){
            return Result.success((List<GoodsVo>)redisTemplate.opsForValue().get(RedisHeader.goodsHeaderName+"getAll"));
        }
        List<GoodsVo> goodsVos=goodsService.selectAll();
        redisTemplate.opsForValue().set(RedisHeader.goodsHeaderName+"getAll",goodsVos);
        return Result.success(goodsVos);
    }
    @ApiOperation("查询所有商品")
    @GetMapping("/getAllExcept/{id}")
    @PreAuthorize("hasAuthority('user')")
    public Result<List<GoodsVo>> getAll(@PathVariable Long id){
        if(redisTemplate.hasKey(RedisHeader.goodsHeaderName+"getAllExcept"+id)){
            return Result.success((List<GoodsVo>)redisTemplate.opsForValue().get(RedisHeader.goodsHeaderName+"getAllExcept"+id));
        }
        List<GoodsVo> goodsVos=goodsService.getAllExcept(id);
        redisTemplate.opsForValue().set(RedisHeader.goodsHeaderName+"getAllExcept"+id,goodsVos);
        return Result.success(goodsVos);
    }
    @ApiOperation("查询商品根据用户id")
    @GetMapping("/getGoodsByUserId/{id}")
    @PreAuthorize("hasAuthority('user')")
    public Result<List<GoodsVo>> getGoodsByUserId(@PathVariable Long id){
        List<GoodsVo> goods=goodsService.getGoodsByUserId(id);
        return Result.success(goods);
    }
    @ApiOperation("添加商品")
    @PostMapping("/addGoods")
    @PreAuthorize("hasAuthority('user')")
    public Result addGoods(@RequestBody GoodsRequestDto goodsRequestDto){
        cleanCache(RedisHeader.goodsHeaderName);
        GoodsCreateDto goodsCreateDto=goodsRequestDto.getGoodsCreateDto();
        List<String>urls=goodsRequestDto.getUrls();
        long gid=goodsService.insertGoods(goodsCreateDto);
        goodsService.addGoodsPhotos(urls,gid);
        return Result.success();
    }
    @ApiOperation("根据名称查询商品")
    @GetMapping("/getOneByName")
    public Result<List<GoodsVo>> selectGoodById(String goodsName){
        List<GoodsVo> goods = goodsService.selectByName(goodsName);
        return Result.success(goods);
    }
    @ApiOperation("根据id查询商品")
    @GetMapping("/getOne")
    public Result<GoodsVo> selectGoodById(long id){
        GoodsVo goods = goodsService.selectById(id);
        return Result.success(goods);
    }
    @ApiOperation("根据商品id查询商品首图片")
    @GetMapping("/findBigPhoto")
    public Result<String> findBigPhoto(long goodId){
        if(redisTemplate.hasKey(RedisHeader.goodsPhoto + goodId)){
            return Result.success(((List<String>) redisTemplate.opsForValue().get(RedisHeader.goodsPhoto + goodId)).get(0));
        }
        List<String> photos = goodsService.findPhotosById(goodId);
        redisTemplate.opsForValue().set(RedisHeader.goodsPhoto+goodId,photos.get(0));
        return Result.success(photos.get(0));
    }
    @ApiOperation("根据商品id查询商品所有图片")
    @GetMapping("/findBigPhotos")
    public Result<List<String>> findBigPhotos(long goodId){
        if(redisTemplate.hasKey(RedisHeader.goodsPhoto + goodId)){
            return Result.success((List<String>) redisTemplate.opsForValue().get(RedisHeader.goodsPhoto + goodId));
        }
        List<String> photos = goodsService.findPhotosById(goodId);
        redisTemplate.opsForValue().set(RedisHeader.goodsPhoto+goodId,photos);

        return Result.success(photos);
    }

    //TODO  下面不好区分，我认为用户和管理员都可以使用
    @ApiOperation("修改商品")
    @PostMapping("/update")
    public Result selectGoodById(@RequestBody GoodsUpdateDto goodsUpdateDto){
        cleanCache("goods*");
        goodsService.updateGoods(goodsUpdateDto);
        return Result.success();
    }
    @ApiOperation("删除商品")
    @DeleteMapping("/{gid}")
    public Result deleteGoods(@PathVariable String gid){
        cleanCache("goods*");
        goodsService.deleteGoods(Long.parseLong(gid));
        return Result.success();
    }

    private void cleanCache(String pattern){
        Set keys = redisTemplate.keys(pattern);
        redisTemplate.delete(keys);
    }
}
